package com.handler;

import com.util.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
@ResponseBody
public class InterfaceExceptionHandler {

    /**
     * 拦截所有运行时的全局异常   
     */
    @ExceptionHandler(RuntimeException.class)
//    @ResponseBody
//    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Response runtimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return Response.createError("系统运行异常", e.toString());
    }

    /**
     * 拦截自定义业务异常   
     */
    @ExceptionHandler(BizException.class)
//    @ResponseBody
//    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Response bizException(BizException e) {
        log.error(e.getMessage(), e);
        return Response.createError(e.getMessage(), e.toString());
    }

    /**
     * 全局系统异常捕获处理
     */
    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Response exception(Exception e) {
        log.error(e.getMessage(), e);
        return Response.createError("系统异常", e.toString());
    }

    @ExceptionHandler(value = BindException.class)
//    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Response bindException(BindException e) {
        String message = "";
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            message = fieldError.getDefaultMessage();
        }
        return Response.createError(message);
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
//    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Response parmeterNotValidException(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage)
            .collect(Collectors.joining());
        return Response.createError(message);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
//    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Response methodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = "";
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            message = fieldError.getDefaultMessage();
        }
        return Response.createError(message);
    }
}


